import router from './controller';
import config from './config';

const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
    // 导入controller middleware:
const rest = require('./helper/rest')
const serve = require('koa-static');
const cors = require('koa-cors')
const path = require('path')
const fs = require('fs')
const send = require('koa-send');
const mount = require('koa-mount')
const session = require('koa-session')
const uuidv1 = require('uuid/v1');
const app = new Koa()
import Helper from './helper/MiddleHelper'
import { isNull, isUndefined } from 'util';

var helper = new Helper()

app.use(cors())
app.use(bodyParser())
app.use(serve(path.resolve(config.fileDir)))
app.use(serve(path.join(__dirname, '..', 'client/dist')));

app.keys = ['some secret'];  /* cookie的签名 */

const CONFIG = {
    key: 'koa:sess', /* 默认的cookie签名 */
    maxAge: 86400000,/* cookie的最大过期时间 */
    autoCommit: true, /** (boolean) automatically commit headers (default true) */
    overwrite: true, /** 无效属性 */
    httpOnly: true, /** (boolean) httpOnly or not (default true) */
    signed: true, /** 默认签名与否 */
    rolling: false, /** 每次请求强行设置cookie */
    renew: false, /** cookie快过期时自动重新设置*/
};

app.use(session(CONFIG, app));

app.use(function(ctx, next) {
    if (ctx.request.path.indexOf("/api") != 0) {
        ctx.response.type = 'html';
        ctx.response.body = fs.readFileSync(path.join(__dirname, '..', 'client/dist/index.html'), 'utf8');
    } else {
        var userId = ctx.cookies.get("userId");
        if(!userId){
            var key = uuidv1();
            ctx.cookies.set("userId",key,{
                maxAge:1000*60*60
            })
            userId = key;
        }
        console.log('userId',userId)
        // ctx.session.userId= userId
        ctx.state.user = { userId: userId }
        return next()
    }
})

app.use(rest.restify())
app.use(router.routes())



export default app.listen(config.port, () => {
    console.log(`App is listening on ${config.port}.`);
});